package com.gmics.unifiq.adapter;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.gmics.android.R;
import com.gmics.unifiq.controller.EntityController;
import com.gmics.unifiq.entity.Avatar;
import com.gmics.unifiq.entity.OpenEvent;

public class AvatarAdapter extends BaseAdapter {
	private Context context;
	private ArrayList<Avatar> avatarArr;

	public AvatarAdapter(Context context, ArrayList<Avatar> avatarArr) {
		this.context = context;
		this.avatarArr = avatarArr;
	}

	@Override
	public int getCount() {
		return avatarArr.size();
	}

	@Override
	public Object getItem(int position) {
		return avatarArr.get(position);
	}

	@Override
	public long getItemId(int position) {
		return avatarArr.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	 
			View gridView = new View(context);
			gridView = inflater.inflate(R.layout.change_avatar_grid_item, null);
 
			ImageView imageView = (ImageView) gridView.findViewById(R.id.avatar_icon);
			TextView nameTV = (TextView) gridView.findViewById(R.id.avatar_name);
			
			if (convertView != null) {
				gridView = convertView;
			}
			else{
				imageView.setPadding(0, 0, 0, 15);
				nameTV.setPadding(0, 0, 0, 5);
			}

			nameTV.setText(avatarArr.get(position).getName());
			
			try {
				  URL url = new URL(avatarArr.get(position).getImagePath()); 
				 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				 connection.setRequestMethod("POST");
				 connection.setRequestProperty("Connection", "close"); 
				 connection.connect();
				 Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
				 //Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(prodArr.get(position).getProductImagePath()).getContent());
				  imageView.setImageBitmap(bitmap); 
			} catch (MalformedURLException e) {
			  e.printStackTrace();
			} catch (IOException e) {
			  e.printStackTrace();
			}
			return gridView;
	}
}